<template>
  <div class="box">
    <vxe-toolbar>
      <template v-slot:buttons>
        <vxe-button @click="insertEvent">新增</vxe-button>
        <vxe-button @click="validEvent">校验</vxe-button>
        <vxe-button @click="fullValidEvent">完整校验</vxe-button>
      </template>
    </vxe-toolbar>
    <vxe-table
      ref="xTable"
      border
      resizable
      keep-source
      :data="tableData"
      :edit-rules="validRules"
      :edit-config="{trigger: 'click', mode: 'cell', showStatus: true, icon: 'fa fa-pencil'}"
      @edit-closed="editClosedEvent"
    >
      <vxe-table-column type="seq" width="60" title="序号"></vxe-table-column>
      <vxe-table-column field="name" title="Name" :edit-render="{name: 'input'}"></vxe-table-column>
      <vxe-table-column field="role" title="Role" :edit-render="{name: 'input'}"></vxe-table-column>
      <vxe-table-column field="sex" title="Sex" :edit-render="{name: '$select', options: sexList}"></vxe-table-column>
      <vxe-table-column field="num6" title="Number" :edit-render="{name: '$input', props: {type: 'number'}}"></vxe-table-column>
      <vxe-table-column field="date12" title="Date" :edit-render="{name: '$input', props: {type: 'date'}}"></vxe-table-column>
    </vxe-table>
  </div>
</template>

<script>
import tableData from './a.json'
import sexList from './sexList.json'
export default {
  data () {
    const nameValid = ({ cellValue }) => {
      return new Promise((resolve, reject) => {
        if (cellValue.length < 3 || cellValue.length > 50) {
          reject(new Error('名称长度在 3 到 50 个字符之间'))
        } else {
          resolve()
        }
      })
    }
    const roleValid = ({ cellValue }) => {
      if (
        cellValue &&
        !['前端', '后端', '设计师', '项目经理', '测试'].includes(cellValue)
      ) {
        return Promise.reject(new Error('角色输入不正确'))
      }
    }
    return {
      tableData: tableData,
      sexList: sexList,
      validRules: {
        name: [
          { required: true, message: '名称必须填写' },
          { validator: nameValid }
        ],
        role: [{ validator: roleValid }],
        sex: [
          { required: true, message: '性别必须填写' },
          { pattern: /^[0,1]{1}$/, message: '格式不正确' }
        ],
        age: [{ pattern: '^[0-9]{0,3}$', message: '格式不正确' }],
        date12: [
          { required: true, message: '日期必须填写' }
        ]
      }
    }
  },
  created () {
    // this.tableData = window.MOCK_DATA_LIST.slice(0, 6)
    this.findSexList()
  },
  methods: {
    findSexList () {
      // return XEAjax.get('/api/conf/sex/list').then(data => {
      //   this.sexList = data
      // })
    },
    // 修改保存数据
    editClosedEvent ({ row, column }) {
      const xTable = this.$refs.xTable
      const field = column.property
      const cellValue = row[field]
      // 判断单元格值是否被修改
      if (xTable.isUpdateByRow(row, field)) {
        setTimeout(() => {
          this.$XModal.message({
            message: `局部保存成功！ ${field}=${cellValue}`,
            status: 'success'
          })
          // 局部更新单元格为已保存状态
          this.$refs.xTable.reloadRow(row, null, field)
        }, 300)
      }
    },
    // 插入一条新数据
    async insertEvent () {
      const { row: newRow } = await this.$refs.xTable.insert()
      // 插入一条数据并触发校验
      const errMap = await this.$refs.xTable.validate(newRow).catch(errMap => errMap)
      if (errMap) { console.log(errMap) }
    },
    // 校验数据
    async validEvent() {
      const errMap = await this.$refs.xTable.validate().catch(errMap => errMap)
      if (errMap) {
        this.$XModal.message({ status: 'error', message: '校验不通过！' })
      } else {
        this.$XModal.message({ status: 'success', message: '校验成功！' })
      }
    },
    // 完整校验
    async fullValidEvent() {
      const errMap = await this.$refs.xTable
        .fullValidate()
        .catch(errMap => errMap)
      if (errMap) {
        const msgList = []
        Object.values(errMap).forEach(errList => {
          errList.forEach(params => {
            const { rowIndex, column, rules } = params
            rules.forEach(rule => {
              msgList.push(
                `第 ${rowIndex} 行 ${column.title} 校验错误：${rule.message}`
              )
            })
          })
        })
        this.$XModal.message({
          status: 'error',
          message: () => {
            return [
              <div class="red" style="max-height: 400px;overflow: auto;">
                {msgList.map(msg => (
                  <div>{msg}</div>
                ))}
              </div>
            ]
          }
        })
      } else {
        this.$XModal.message({ status: 'success', message: '校验成功！' })
      }
    },
  }
}
</script>

<style>

</style>